﻿(function () {
    'use strict';

    angular.module('app.services', [])        
        .factory('$utils', utilBlock)
        .factory('msgHubService', msgHubBlock);

    /** @ngInject */
    function utilBlock($http, $httpParamSerializer, $rootScope, $state, $uibModal, cfpLoadingBar, $const) {
        var util = {
            get: function (url, data, callback) {
                if (data) {
                    if (typeof (data) == "object") url += "?" + $httpParamSerializer(data);
                    else url += "?" + data;
                }
                cfpLoadingBar.start();
                var headers = { token: "xxx112==" };
                $http({
                    method: "GET",
                    url: url,
                    crossDomain: true,
                    params: data,
                    headers: headers
                }).then(function successCallback(response) {
                    
                    //console.log(response);
                    if (callback != null)
                        callback(response);
                    cfpLoadingBar.complete();

                }, function errorCallback(response) {

                    cfpLoadingBar.complete();
                    //console.error(response);
                    alert("Error occured: " + response.status + "/" + response.statusText);

                });
            },
            post: function (url, data, callback) {
                var headers = { token: "xxx221==" };
                cfpLoadingBar.start();
                $http({
                    method: "POST",
                    url: url,
                    crossDomain: true,
                    params: data,
                    headers: headers
                }).then(function successCallback(response) {

                    //console.log(response);
                    if (callback != null)
                        callback(response);
                    cfpLoadingBar.complete();

                }, function errorCallback(response) {
                    
                    cfpLoadingBar.complete();
                    //console.error(response);
                    alert("Error occured: " + response.status + "/" + response.statusText);

                });
            },
            loadingShow: function () {
                cfpLoadingBar.start();
            },
            loadingHide: function () {
                cfpLoadingBar.complete();
            },
            showModal: function (modalId, controller, viewData, callback) { //msg: 提示文本 callback: 点击确认后执行的回调方法
                var modalInstance = $uibModal.open({
                    animation: true,
                    size: 'md',
                    templateUrl: modalId,
                    controller: controller,
                    controllerAs: 'vm',
                    backdrop: "static",
                    windowClass: 'my-modal',
                    resolve: {
                        '$input': function () {  //传当前页面的值到模态框
                            return { 'viewData': viewData };
                        }
                    }
                });
                modalInstance.result.then(function (arg) {  //模态框回调
                    if (callback != null)
                        callback(arg);
                });
            },
            getTimeString: function (oDate) {
                if (!oDate) oDate = new Date();
                var hour = oDate.getHours();
                var mins = oDate.getMinutes();
                var secd = oDate.getSeconds();
                var shour = hour > 9 ? hour : '0' + hour;
                var smins = mins > 9 ? mins : '0' + mins;
                var ssecd = secd > 9 ? secd : '0' + secd;
                return shour + ':' + smins + ':' + ssecd;
            }
        };

        return util;
    }

    /** @ngInject */
    function msgHubBlock($rootScope, Hub, $, $const) {
        var these = this;        

        var _vm = {};  //view model
        these.init = function (vm) {
            _vm = vm;
        };

        var msgHub = new Hub($const.signalrHub, {
            logging: true, // 启用日志
            rootPath: $rootScope.signalrUrl, // 服务器地址
            queryParams: { role: 'portal' },
            listeners: { // 服务端调用客户端方法
                receiveHeartbeat: function (data) {
                    //console.log(data);
                    if (these.receiveHeartbeat)
                        these.receiveHeartbeat(data);
                },
                receiveCPU: function (data) {
                    //console.log(data);
                    if (these.receiveCPU)
                        these.receiveCPU(data);
                },
                receiveDisk: function (data) {
                    //console.log(data);
                    if (these.receiveDisk)
                        these.receiveDisk(data);
                },
                receiveMemory: function (data) {
                    //console.log(data);
                    if (these.receiveMemory)
                        these.receiveMemory(data);
                },
                receiveCurrentConnection: function (data) {
                    //console.log(data);
                    if (these.receiveCurrentConnection)
                        these.receiveCurrentConnection(data);
                },
                receiveMonitor: function (data) {
                    //console.log(data);
                    if (these.receiveMonitor)
                        these.receiveMonitor(data);
                },
                receiveMessage: function (msg) {
                    //console.log(msg);
                    if (these.receiveMessage)
                        these.receiveMessage(msg);
                }
            },
            methods: ['pushPingOutput', 'pushTelnetOutput'], // 定义客户端调用服务端的方法
            errorHandler: function (error) { // 异常处理
                console.error(error);
                alert(error);
            },
            stateChanged: function (state) {
                switch (state.newState) {
                    case $.signalR.connectionState.connecting:  //0
                        console.log('Connecting to the remote server...');
                        break;
                    case $.signalR.connectionState.connected:  //1
                        console.log('The connection is established.');
                        if (these.onHubConnected) { these.onHubConnected(); }
                        $rootScope.alertMessage = null;
                        $rootScope.$apply();
                        break;
                    case $.signalR.connectionState.reconnecting:  //2
                        console.log('Reconnecting to the remote server...');
                        $rootScope.alertMessage = 'Reconnecting to the remote server...';
                        $rootScope.$apply();
                        break;
                    case $.signalR.connectionState.disconnected:  //4
                        console.log('The connection is terminated.');
                        if (these.onHubDisconnected) { these.onHubDisconnected(); }
                        $rootScope.alertMessage = 'The connection is terminated.';
                        $rootScope.$apply();
                        break;
                }
            }
        });

        these.onHubConnected = null;
        these.onHubDisconnected = null;        
        these.sendPingOutput = function (host) {
            if (msgHub.connection.state == $.signalR.connectionState.connected)
                msgHub.pushPingOutput(host);
            else
                alert('The operation can not be performed, please check the connection.');
        };
        these.sendTelnetOutput = function (host, port) {
            if (msgHub.connection.state == $.signalR.connectionState.connected)
                msgHub.pushTelnetOutput(host, port);
            else
                alert('The operation can not be performed, please check the connection.');
        };
        return these;
    }

})();
